module.exports = app => {
    const router = require('express').Router();
    const mongooes = require('mongoose');
    const Article = mongooes.model('Article');
    const Category = mongooes.model('Category');
    const Hero = mongooes.model('Hero');

    // 导入新闻数据
    router.get('/news/init', async (req, res) => {
        const parent = await Category.findOne({
            name: '新闻分类'
        });
        const cats = await Category.find().where({
            parent
        }).lean();
        const newsTitles = ["“Spark More”王者荣耀打造玩家新触点，让游戏焕活更多传统文化的可能", "腾讯游戏年度发布会，一张图带你看天美最新动态！", "集合，准备上船！——谁是峡谷最佳龙舟手？", "英雄调整情报丨貂蝉加强，赵云优化", "峡谷端午过节指南", "6月30日全服不停机更新公告", "6月29日体验服停机更新公告", "6月29日体验服不停机更新公告", "6月28日体验服停机更新公告", "6月26日体验服停机更新公告", "赛季冲刺有福利，挑战领好礼", "荣耀中国节·峡谷龙舟赛，参与必得粽情泛舟回城特效（新）", "峡谷庆端午，好礼领不停", "恭喜TS夺得2020年KPL春季赛总冠军，多重福利来袭", "应援KPL春决得好礼，上官婉儿-天狼绘梦者即将开售", "2020年王者荣耀世界冠军杯小组赛赛程出炉", "2020年王者荣耀世界冠军杯第二轮选拔赛 加赛及抽签规则", "世冠小组赛抽签仪式6月28日现场直播，小组赛之战一触即发！", "2020年王者荣耀世界冠军杯（KCC）赛事规则", "无惧挑战向阳而生，TS冠军之夜今日18:00惊喜来袭"];
        const newsList = newsTitles.map(title => {
            const randCats = cats.slice(0).sort((a, b) => Math.random() - 0.5);
            return {
                title,
                categories: randCats.slice(0, 2)
            }
        });
        await Article.deleteMany({});
        await Article.insertMany(newsList);
        res.send(newsList);
    });


    // 新闻列表接口
    router.get('/news/list', async (req, res) => {
        const parent = await Category.findOne({
            name: '新闻分类'
        });

        // 关联查询
        const cats = await Category.aggregate([
            {$match: {parent: parent._id}},
            {$lookup: {from: 'articles', localField: '_id', foreignField: 'categories', as: 'newsList'}},
            {$addFields: {newsList: {$slice: ['$newsList', 5]}}}
        ])
        const subCats = cats.map(v => v._id);
        cats.unshift({
            name: '热门',
            newsList: await Article.find().limit(5).where({
                categories: {$in: subCats}
            }).populate('categories').lean()
        });

        cats.map(async cat => {
            cat.newsList.map(news => {
                news.categoryName = (cat.name === '热门') ? news.categories[0].name : cat.name
                return news;
            });
            return cat;
        });
        res.send(cats);
    });

    router.get('/heroes/list', async (req, res) => {
        const parent = await Category.findOne({
            name: '英雄'
        })

        const cats = await Category.aggregate([
            {$match: {parent: parent._id}},
            {
                $lookup: {
                    from: 'heros',
                    localField: '_id',
                    foreignField: 'categories',
                    as: 'herosList'
                }
            }
        ])
        const subCats = cats.map(v => v._id);
        cats.unshift({
            name: '热门',
            herosList: await Hero.find().limit(10).where({
                categories: {$in: subCats}
            }).lean()
        });

        cats.map(async cat => {
            cat.herosList.map(news => {
                news.categoryName = (cat.name === '热门') ? news.categories[0].name : cat.name
                return news;
            });
            return cat;
        });

        res.send(cats);
    })

    // 文章详情
    router.get('/articles/:id', async (req, res) => {
        const data = await Article.findById(req.params.id).lean();
        data.related = await Article.find().where({
            categories: { $in: data.categories }
        }).limit(2)
        res.send(data)
    })

    // 英雄详情
    router.get('/heroes/:id', async (req, res) => {
        const data = await Hero.findById(req.params.id).populate('categories items1 items2 partners.hero').lean();
        res.send(data);
    })

    app.use('/web/api', router);
}
